import { useRequest } from "ahooks"
import { Button, DatePicker, DatePickerProps, Empty, Select, Space, Spin } from "antd"
import { queryChargeDataAnalysis, QueryChargeDataAnalysisParamsTimeType, QueryChargeDataAnalysisParamsStubType, ChargeDataAnalysis } from "@/pages/home/service"
import { styled } from '@umijs/max'
import { Chart } from '@antv/g2';
import { useEffect, useRef, useState } from "react";
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import { enum2options } from "@/utils/enum2options";
import RadioButton from "@/components/RadioButton2";
import { Card } from "@/components/Card";

const Content = styled.div`
  width: 100%;
  height: 100%;

  .tabs {
    width: 100%;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
  }

  .chart-area {
    width: 100%;
    height: 380px;
    position: relative;

    .empty {
      position: absolute;
      inset: 0;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
`

enum LineTab {
  充电量分析 = 'power',
  充电次数分析 = 'num',
  订单金额分析 = 'totalMoney',
  服务费分析 = 'serviceMoney',
}

const setChartData = (chart: Chart, data: Partial<ChargeDataAnalysis>[], lineTab: LineTab) => {
  let tooltip = '', unit = ''
  let _data = [...data]
  switch (lineTab) {
    case LineTab.充电量分析: tooltip = '充电量(度):'; unit = '度'; break
    case LineTab.充电次数分析: tooltip = '充电次数(次):'; unit = '次'; break
    case LineTab.订单金额分析: tooltip = '订单金额(元):'; unit = '元'; break
    case LineTab.服务费分析: tooltip = '服务费金额(元):'; unit = '元'; break
  }
  chart.clear()
  chart.data(_data || [])
  chart.area()
    .encode('x', 'day')
    .encode('y', lineTab)
    .encode('shape', 'smooth')
    .style('opacity', 0.2)

  chart.interaction('tooltip', {
    render: (event: any, args: any) => {
      return `
        <div>
          <div>${args.title}</div>
          <div style="display: flex; gap: 12px;">
            <span>${tooltip}</span>
            <span>${args.items[0].value}</span>
          </div>
        </div>
      `
    }
  })

  chart
    .line()
    .encode('x', 'day')
    .encode('y', lineTab)
    .encode('shape', 'smooth')
    .transform({
      type: 'sample',
      thresholds: 200,
      strategy: 'max',
    })

  chart.point().encode('x', 'day')
  .encode('y', lineTab).style('fill', 'white').tooltip(false)
  
  chart.axis('x', {
    title: false,
    labelAutoRotate: false,
  })
  chart.axis('y', {title: false})

  chart.text().style({
    x: 10, // 像素坐标
    y: -20, // 像素坐标
    text: `单位: ${unit}`,
    textAlign: 'center',
    fontSize: 12,
    textBaseline: 'middle',
    fill: '#aaaaaa'
  })

  chart.render()
}

let timer: NodeJS.Timeout

const renderChart = (chart: Chart, data: Partial<ChargeDataAnalysis>[], lineTab: LineTab) => {
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    setChartData(chart, data, lineTab)
  }, 300)
}

const TerminalStatusCard: React.FC = () => {
  const lineChart = useRef<Chart>()
  const [timeType, setTimeType] = useState<QueryChargeDataAnalysisParamsTimeType>(QueryChargeDataAnalysisParamsTimeType.按天);
  const [stubType, setStubType] = useState<QueryChargeDataAnalysisParamsStubType>(QueryChargeDataAnalysisParamsStubType.全部);
  const [dates, setDates] = useState<[Dayjs, Dayjs]>([dayjs().subtract(32, 'days'), dayjs().subtract(1, 'days')]);
  const [lineTab, setLineTab] = useState<LineTab>(LineTab.充电量分析);
  const { data, run, loading, mutate } = useRequest(queryChargeDataAnalysis, {
    manual: true,
    throttleWait: 500,
    onSuccess: (data, params) => {
      let _start = dayjs(params[0].beginDay)
      const _end = dayjs(params[0].endDay)
      const _data: ChargeDataAnalysis[] = []
      while (!_start.isAfter(_end, 'day')) {
        const _day = _start.format('YYYYMMDD')
        const _d = data.data.find(item => item.day === _day)
        if (_d) {
          _data.push({..._d, num: parseInt(_d.num as unknown as string)})
        } else {
          _data.push({
            day: _day,
            num: 0,
            power: 0,
            serviceMoney: 0,
            totalMoney: 0,
          })
        }
        _start = _start.add(1, 'day')
      }
      mutate({code: '200', data: _data, text: '', totalCount: 0})
      renderChart(lineChart.current!, _data, lineTab)
    }
  })

  const onTimeTypeChange = (value: QueryChargeDataAnalysisParamsTimeType) => {
    setTimeType(value)
    switch (value) {
      case QueryChargeDataAnalysisParamsTimeType.按天: setDates([dayjs().subtract(30, 'days'), dayjs()]); break
      case QueryChargeDataAnalysisParamsTimeType.按月: setDates([dayjs().subtract(1, 'month'), dayjs().subtract(1, 'month')]); break
    }
  }

  const doSearch = () => {
    run({
      timeType, stubType: stubType === 0 ? undefined : stubType,
      beginDay: dates[0].format(timeType === QueryChargeDataAnalysisParamsTimeType.按天 ? 'YYYYMMDD' : 'YYYYMM'),
      endDay: dates[1].format(timeType === QueryChargeDataAnalysisParamsTimeType.按天 ? 'YYYYMMDD' : 'YYYYMM'),
      infoType: 2,
    }, localStorage.Authorization2)
  }

  const onLineTabChange = (value: LineTab) => {
    setLineTab(value)
    renderChart(lineChart.current!, data?.data || [], value)
  }

  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    if (!current.isBefore(dayjs(), 'day')) return true
    if (from) {
      return Math.abs(current.diff(from, 'days')) >= 31;
    }

    return false;
  }

  useEffect(() => {
    lineChart.current = new Chart({
      container: 'lineDiv',
      autoFit: true,
      height: 380,
      paddingTop: 10,
    })
    doSearch()
  }, []);

  return <Card
    header='充电数据分析'
    className="row"
  >
    <Content>
      <Space style={{marginBottom: 20}} size={20}>
        <Space>
          <span>统计时间:</span>
          <Select
            value={timeType}
            onChange={onTimeTypeChange}
            options={enum2options(QueryChargeDataAnalysisParamsTimeType)}
            allowClear={false}
          />
          <DatePicker.RangePicker
            value={dates}
            picker={timeType === QueryChargeDataAnalysisParamsTimeType.按天 ? 'date' : 'month'}
            onChange={(values) => setDates(values as any)}
            disabledDate={disabledDate}
            style={{width: 260}}
          />
        </Space>
        {/* <Space>
          <span>枪选择:</span>
          <Select
            value={stubType}
            onChange={setStubType}
            options={enum2options(QueryChargeDataAnalysisParamsStubType)}
          />
        </Space> */}
        <Button type="primary" onClick={() => doSearch()} loading={loading}>查询</Button>
      </Space>
      <div className="tabs">
        <RadioButton<LineTab>
          value={lineTab}
          onChange={onLineTabChange}
          items={enum2options(LineTab)}
        />
      </div>
      <Spin spinning={loading}>
        <div className="chart-area">
          <div id="lineDiv"></div>
          <div className="empty" hidden={!!data?.data.length}>
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
          </div>
        </div>
      </Spin>
    </Content>
  </Card>
}

export default TerminalStatusCard